'use strict'
let { Contexts, Op } = require('../model');

let fn_getList = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || "";
    console.log(keyword);
    if (keyword) {
        let result = await Contexts.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { title: keyword },
                    { talk: keyword },
                    { context: keyword },
                    { sort: keyword },
                    { author: keyword },
                    { Ftime: keyword }
                ]
            }, order: ['id']
        })
        ctx.body = {
            code: 1000,
            data: result,
            msg: '执行成功！'
        }
    } else {
        let result = await Contexts.findAll({
            order: ['id']
        })
        console.log(result);
        ctx.body = {
            code: 1000,
            data: result,
            msg: '执行成功！'
        }
    }
}

let fn_getById = async (ctx, next) => {
    let id = ctx.request.params.id;
    let idobj = await Contexts.findByPk(id);
    if (idobj) {
        ctx.body = {
            code: 1000,
            data: idobj,
            msg: '查询成功！'
        }
    } else {
        ctx.body = {
            code: 404,
            data: idobj,
            msg: '查询失败！'
        }
    }
}

let fn_postAdd = async (ctx, next) => {
    let obj = ctx.request.body;
    await Contexts.create(obj);
    ctx.body = {
        code: 1000,
        data: obj,
        msg: '添加成功！'
    }
}

let fn_putUp = async (ctx, next) => {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    let idobj = await Contexts.findByPk(id);
    if (idobj) {
        Contexts.update(obj, {
            where: {
                id: id
            }
        });
        ctx.body = {
            code: 1000,
            data: obj,
            msg: '修改成功！'
        }
    } else {
        ctx.body = {
            code: 900,
            data: '',
            msg: '修改失败！'
        }
    }
}

let fn_deleteDel = async (ctx, next) => {
    let id = ctx.request.params.id;
    let idobj = await Contexts.findByPk(id);
    if (idobj) {
        Contexts.destroy(idobj);
        ctx.body = {
            code: 1000,
            data: { id },
            msg: '删除成功！'
        }
    } else {
        ctx.body = {
            code: 900,
            data: null,
            msg: '删除失败！'
        }
    }
}

module.exports = {
    'get /contexts': fn_getList,
    'get /contexts/:id': fn_getById,
    'post /contexts': fn_postAdd,
    'put /contexts/:id': fn_putUp,
    'delete /contexts/:id': fn_deleteDel
}